use std::collections::HashMap;
use std::vec;

use model_graph_types::database::DataSource;
use model_graph_types::datasource::{
    ClassRelationCondition, DataSourceConnector, DeleteCondition, DeleteOptions, InsertOptions,
    QueryCondition, QuerySelect, RelationCondition, UpdateCondition, UpdateOptions,
};

use model_graph_types::modeling::{
    system_meta_database, Class, ClassGetter, ClassPersistence, ClassRelation,
    DataSourceClassRelationMapping, DataSourceClassRelationMappingBuilder, MetaConnector,
    RelationDirection, Value, ValueOperator,
};

use crate::connector::SimpleDataSourceConnector;
use crate::modeling_connector::SimpleMetaConnector;

pub fn genertate_query_one_sql(
    datasource: &DataSource,
    clazz: &Class,
    keys: &Vec<String>,
    mapping: ClassPersistence,
) -> anyhow::Result<String> {
    //
    //查询主键
    let key_names = &clazz.primary_key;
    let where_keys = key_names
        .split(",")
        .collect::<Vec<_>>()
        .iter()
        .map(|key_name| format!("{} = ? ", key_name))
        .collect::<Vec<String>>()
        .join(" and ");

    Ok(format!(
        "SELECT * FROM {} WHERE {}",
        mapping.table_name, where_keys
    ))
}

struct RelationDatabaseMapping {}

async fn genertate_insert_data_sql(
    meta_datasource: &DataSource,
    class_identifier: &String,
    values: HashMap<String, Value>,
    options: Option<InsertOptions>,
) -> anyhow::Result<(String, Vec<Value>)> {
    let modeling = SimpleMetaConnector::new_with_meta_datasource(&Some(meta_datasource.clone()))?;
    let ds_connector = SimpleDataSourceConnector::default();
    let clazz = modeling.get_class(class_identifier).await?;
    // //获取映射
    let mapping = modeling.get_class_persistence(class_identifier).await?;

    let mut table_name = clazz.name.clone();
    table_name = mapping.table_name.clone();

    let mut args: Vec<Value> = vec![];

    let mut column_names: Vec<String> = vec![];
    let mut values_names: Vec<String> = vec![];
    //获取所有的字段映射
    for column in mapping.columns {
        //取值
        if let Some(v) = values.get(&column.column_name) {
            column_names.push(column.column_name);
            values_names.push(String::from("?"));

            //
            args.push(v.clone());
        } else {
            //默认值
        }
    }

    let sql = format!(
        "INSERT INTO {}({})VALUES({})",
        table_name,
        column_names.join(","),
        values_names.join(",")
    );

    Ok((sql, args))
}

async fn genertate_delete_data_sql(
    meta_datasource: &DataSource,
    class_identifier: &String,
    conditions: DeleteCondition,
    options: Option<DeleteOptions>,
) -> anyhow::Result<(String, Vec<Value>)> {
    let modeling = SimpleMetaConnector::new_with_meta_datasource(&Some(meta_datasource.clone()))?;
    let ds_connector = SimpleDataSourceConnector::default();
    let clazz = modeling.get_class(class_identifier).await?;
    // //获取映射
    let mapping = modeling.get_class_persistence(class_identifier).await?;

    let mut table_name = clazz.name.clone();
    table_name = mapping.table_name.clone();

    Ok((String::new(), vec![]))
}

async fn genertate_update_data_sql(
    meta_datasource: &DataSource,
    class_identifier: &String,
    conditions: UpdateCondition,
    values: HashMap<String, Value>,
    options: Option<UpdateOptions>,
) -> anyhow::Result<(String, Vec<Value>)> {
    let modeling = SimpleMetaConnector::new_with_meta_datasource(&Some(meta_datasource.clone()))?;
    let ds_connector = SimpleDataSourceConnector::default();
    let clazz = modeling.get_class(class_identifier).await?;
    // //获取映射
    let mapping = modeling.get_class_persistence(class_identifier).await?;

    let mut table_name = clazz.name.clone();
    table_name = mapping.table_name.clone();

    Ok((String::new(), vec![]))
}
